package br.com.guardaroupavirtual.helper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.json.JSONObject;

import br.com.guardaroupavirtual.facade.Facade;
import br.com.guardaroupavirtual.model.Usuario;

public class LoginFacebook {

	private static final String client_secret = "34bde374b3f33555415072ccba0ec69e";
    private static final String client_id = "577105732389071"; 
    private static final String redirect_uri = "http://localhost:8080/GRV/loginfbresponse";
 
    public Usuario obterUsuarioFacebook(String code)throws MalformedURLException, IOException {
 
		String retorno = readURL(new URL(this.getAuthURL(code)));
 
		String accessToken = null;
		@SuppressWarnings("unused")
		Integer expires = null;
		String[] pairs = retorno.split("&");
		for (String pair : pairs) {
			String[] kv = pair.split("=");
			if (kv.length != 2) {				
				throw new RuntimeException("Resposta auth inesperada.");				
			} else {
				if (kv[0].equals("access_token")) {
					accessToken = kv[1];
				}
				if (kv[0].equals("expires")) {
					expires = Integer.valueOf(kv[1]);
				}
			}
		}
 
		JSONObject user = new JSONObject(readURL(new URL("https://graph.facebook.com/me?access_token=" + accessToken)));
 		
		Session session = HibernateHelper.getSessionFactory().openSession();
		Transaction transaction = session.beginTransaction();
		
		Facade fachada = Facade.getCurrentInstance();
		
		Usuario usuario = fachada.getUsuarioByIdFacebook(session, user.getString("id"));
		try {			
			if (usuario == null) {
				usuario = new Usuario();
				usuario.setIdFacebook(user.getString("id"));
				usuario.setEmail(user.getString("email"));
				usuario.setSexo(user.getString("gender").equals("male") ? "M" : "F");
				usuario.setAdministrador(false);
				usuario.setDataNascimento(new Date());
				usuario.setMedida("M");
				usuario.setSenha("123");
				fachada.cadastrarUsuario(session, usuario);
				transaction.commit();
			}		
		} catch (Exception e) {
			transaction.rollback();
			e.printStackTrace();
		}
		return usuario;	
 
	}
    
    private String readURL(URL url) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		InputStream is = url.openStream();
		int r;
		while ((r = is.read()) != -1) {
			baos.write(r);
		}
		return new String(baos.toByteArray());
	}
 
	public String getLoginRedirectURL() throws UnsupportedEncodingException {
		return "https://graph.facebook.com/oauth/authorize?client_id="
				+ client_id + "&display=page&redirect_uri=" + URLEncoder.encode(redirect_uri, "UTF-8")
				+ "&scope=email";
	}
 
	public String getAuthURL(String authCode) {
		return "https://graph.facebook.com/oauth/access_token?client_id="
				+ client_id + "&redirect_uri=" + redirect_uri
				+ "&client_secret=" + client_secret + "&code=" + authCode;
	}    
}
